//
//  BKComposeTextView.swift
//  微博
//
//  Created by mac on 16/8/16.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

class BKComposeTextView: UITextView {
    
    //  MARK: -- 懒加载创建控件
    private lazy var placeHolderLabel:UILabel = {
    
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(12)
        label.text = "敲代码和音乐很配偶~"
        label.textColor = UIColor.lightGrayColor()
        
        return label
    
    }()
    
    //提供外界设置占位文字的属性
    //  @IBInspectable 给xib/sb添加可以设置的属性
    @IBInspectable var placeHolder:String?{
    
        didSet{
        
           placeHolderLabel.text = placeHolder
        }
    }
    
    //重写font
    override var font:UIFont? {
    
        didSet {
        
            if font != nil {
            
                placeHolderLabel.font = font
            }
        }
    }
    
    //重写text
    override var text:String? {
    
        didSet {
        
            placeHolderLabel.text = text
        }
    }
    

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    private func setupUI() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    
        addSubview(placeHolderLabel)
        
        //使用系统的约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    @objc private func textChange() {
    
        placeHolderLabel.hidden = hasText()
    }
    
    //给子控件添加约束
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 7
    }
    
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
